<template>
	<view class="page">
		<view class="status-bar" :style="{ 'paddingTop': statusBarHeight + 'px' }"></view>
		<view class="nav-bar">
			<view class="back-btn" @click="onBack">
				<up-icon name="arrow-left" size="20" :bold="true"></up-icon>
			</view>
			上传照片
		</view>
		<up-alert
			 v-if="orderId"
			:center="true"
			description="注意上传照片质量，很多制作失败是因为图片问题"
			type="warning"
		></up-alert>
		<view class="upload-section">
			<!-- 正脸 -->
			<up-upload :fileList="files.fileList1" @afterRead="afterRead1" @delete="deletePic1" name="6" :maxCount="1"
				width="388rpx" height="516rpx" :previewFullImage="false" imageMode="aspectFit">
				<view class="upload-area">
					<img src="https://gamumu.hilumo.com/prod-api/files/down/1963125221775683584.png" alt="camera" class="camera">
				</view>
				<view class="ai-text">*该功能由AI生成、人工智能生成</view>
			</up-upload>
		</view>
		<!-- 上传要求 -->
		<view class="upload-demo">
			<view class="title">上传要求</view>
			<up-row justify="space-between" gutter="10">
				<up-col span="3">
					<img src="https://gamumu.hilumo.com/prod-api/files/down/1970865407481159680.png" alt="上传要求" class="demo-img">
				</up-col>
				<up-col span="3">
					<img src="https://gamumu.hilumo.com/prod-api/files/down/1970865340804308992.png" alt="上传要求" class="demo-img">
				</up-col>
				<up-col span="3">
					<img src="https://gamumu.hilumo.com/prod-api/files/down/1970865252426129408.png" alt="上传要求" class="demo-img">
				</up-col>
				<up-col span="3">
					<img src="https://gamumu.hilumo.com/prod-api/files/down/1970865112458010624.png" alt="上传要求" class="demo-img">
				</up-col>
			</up-row>
		</view>
		<!-- 用户须知 -->
		<view class="alert-msg">
			您上传的照片仅用于所选模板的照片合成,不会被他人使用,我们将严格按照
			<view class="agreement" @click="toPage">隐私协议</view>
			保存、处理、删除相关数据。请勿使用未获得本人授权同意的照片或视频。
		</view>
		<view class="btn-box">
			<!-- orderId 不存在为新制作 -->
			<button class="upload-btn" :class="{'success': files.fileList1.length}" type="default" @click="completeUpload" v-if="!orderId">完成上传</button>
			<!-- orderId 存在为制作失败重新制作 -->
			<button class="upload-btn" :class="{'success': files.fileList1.length}" type="default" @click="remake" v-else>完成上传</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const statusBarHeight = ref(0)
	statusBarHeight.value = uni.getSystemInfoSync()['statusBarHeight']
	const token = ref(null)
	const uuid = ref(null)
	const orderId = ref(null)
	onLoad((option) => {
		uuid.value = option.uuid
		orderId.value = option.orderId
	})
	onShow(() => {
		token.value = uni.getStorageSync('token')
	})
	const activeTab = ref(1)
	const list1 = ref([{
			name: '正脸',
			value: 1
		}
	])

	// 图片位置：正脸、左侧脸、右侧脸
	function clickTab(item, index) {
		activeTab.value = item.value
	}

	// 上传图片
	const files = reactive({
		fileList1: []
	})

	// 删除图片
	const deletePic1 = (event) => {
		files.fileList1.splice(event.index, 1);
	};

	// 新增图片--正脸
	const afterRead1 = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = files.fileList1.length;
		lists.map((item) => {
			files.fileList1.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = files.fileList1[fileListLen];
			files.fileList1.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};
	
	const uploadFilePromise = (url) => {
		const name = new Date().getTime()
		const arr = `${url}`.split('.')
		const ext = `.${arr[arr.length - 1]}`
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: `${getApp().globalData.baseUrl}/prod-api/files/tencentoss/upload`,
				filePath: url,
				name: 'file',
				header: {
					'Authorization': "Bearer " + token.value,
				},
				formData: {
					name,
					ext,
					type: 0,
					ostype: 3,
				},
				success: (res) => {
					const dataJson = JSON.parse(res.data)
					setTimeout(() => {
						resolve(dataJson.file);
					}, 1000);
				},
			});
		});
	};

	// 完成上传
	function completeUpload() {
		const { fileList1 } = files
		
		if(!fileList1.length) {
			uni.showToast({
				icon: 'none',
				title: '请上传正脸照'
			})
			return
		} else if (!fileList1[0].url.uuid) {
			uni.showToast({
				icon: 'none',
				title: '上传中，请稍后'
			})
			return
		}
		// 保存图片信息在storage
		const images = {
			fImg: fileList1[0].url
		}
		uni.setStorageSync('userImages', images)
		// uuid 为 套系uuid
		uni.navigateTo({
			url: `/pages/order/order?uuid=${uuid.value}`
		})
	}
	
	// 重新制作
	function remake() {
		const { fileList1 } = files
		if(!fileList1.length) {
			uni.showToast({
				icon: 'none',
				title: '请上传正脸照'
			})
			return
		}
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/pays/mine/fail/retry/${orderId.value}`,
			method: 'PUT',
			header: {
				'Authorization': "Bearer " + token.value,
			},
			data: {
				frontUrl: fileList1[0].url.url,
			},
			success: (res) => {
				if (res.data.code === 200) {
					uni.reLaunch({
						url: `/pages/order/detail?uuid=${orderId.value}`
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.msg
					})
				}
			},
			fail: (error) => {
				console.log(error)
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}
	
	function toPage() {
		uni.navigateTo({
			url: '/pages/agreement/privacy'
		})
	}
	
	// 返回上一页
	function onBack() {
		uni.navigateBack()
	}
</script>

<style lang="scss" scoped>
	.page {
		padding-bottom: 160rpx;
	}
	.alert {
		padding: 0 20rpx;
	}
	.page {
		background: linear-gradient(180deg, rgba(255, 209, 156, 0.2) 0%, rgba(255, 255, 255, 0.2) 100%), linear-gradient(0deg, #FFFFFF, #FFFFFF), linear-gradient(345.43deg, rgba(255, 126, 24, 0.3) 11.09%, rgba(255, 100, 45, 0.3) 96.87%);
	}
	.nav-bar {
		height: 84rpx;
		line-height: 84rpx;
		padding: 0 20rpx;
		overflow: hidden;
		text-align: center;
		font-family: PingFang SC;
		font-weight: 400;
		font-style: Medium;
		font-size: 32rpx;
		leading-trim: NONE;
		letter-spacing: 0%;
		.back-btn {
			float: left;
			padding-top: 20rpx;
		}
	}
	.tab-box {
		width: 100%;
		position: relative;
		height: 68rpx;
		margin-bottom: 10rpx;

		.custom-tab {
			position: absolute;
			left: 50%;
			top: 0;
			margin-left: -52rpx;
		}
	}

	.upload-section {
		padding: 40rpx 40rpx 40rpx 188rpx;
	}
	.upload-area {
		width: 388rpx;
		height: 516rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		border-radius: 16rpx;
		border: 6rpx solid #ffd19c;
		box-sizing: border-box;
		.camera {
			width: 72rpx;
			height: 72rpx;
			display: block;
		}
	}
	.btn-box {
		padding: 20rpx 40rpx 20rpx;
		padding-bottom: env(safe-area-inset-bottom);
		background: #ffffff;
		position: fixed;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
	}
	.upload-btn {
		width: 422rpx;
		height: 100rpx;
		color: #FFFFFF;
		font-family: PingFang SC;
		font-weight: 500;
		font-style: Heavy;
		font-size: 36rpx;
		leading-trim: NONE;
		line-height: 100rpx;
		letter-spacing: 10%;
		border-radius: 28rpx;
		background: #AEAEAE;
		margin-bottom: 20rpx;
		&.success {
			background: linear-gradient(90deg, #D19973 0%, #EBBD9D 100%);
		}
	}
	.upload-demo {
		width: 670rpx;
		margin: 0 auto 80rpx;
		border-radius: 20px;
		padding: 40rpx 16rpx 20rpx;
		box-sizing: border-box;
		background: #F2F2F2;
		border-radius: 20rpx;
		.title {
			font-family: PingFang SC;
			font-weight: 500;
			font-style: Medium;
			font-size: 28rpx;
			leading-trim: NONE;
			line-height: 34rpx;
			letter-spacing: 0%;
			color: #333333;
			margin-bottom: 20rpx;
		}
		.demo-img {
			width: 158rpx;
			height: 218rpx;
			object-fit: contain;
		}
	}
	::v-deep .u-row {
		flex-wrap: wrap;
	}
	.alert-msg {
		font-family: PingFang SC;
		font-weight: 400;
		font-style: Regular;
		font-size: 20rpx;
		leading-trim: NONE;
		line-height: 34rpx;
		text-align: justify;
		color: #7F7F7F;
		padding: 0 40rpx 30rpx;
		.agreement {
			display: inline;
			color: #D19973;
			text-decoration: underline;
		}
	}
</style>